package com.snail.jj.androiddemos.components.receivers;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.BatteryManager;
import android.util.Log;
import android.widget.Toast;

/**
 * Created by snail on 2017/5/12.
 */

public class NetworkStateReceiver extends BroadcastReceiver {

    private static final String TAG = "NetworkStateReceiver";

    @Override
    public void onReceive(Context context, Intent intent) {

        Log.i(TAG,"NetworkState. Changed");
        if (!isNetworkAvailable(context)) {
            Toast.makeText(context,"network disconnected!",Toast.LENGTH_SHORT).show();
        }

    }

    //TODO:判断网络状态
    public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager mgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo[] networks = mgr.getAllNetworkInfo();
        if (networks != null) {
            for (NetworkInfo networkInfo : networks) {
                if (networkInfo.getState() == NetworkInfo.State.CONNECTED) {
                    return true;
                }
            }
        }
        return false;
    }


    //TODO:电量变化
    public static double getBatteryPercent(Intent intent) {

        int currLevel = intent.getIntExtra(BatteryManager.EXTRA_LEVEL,0);   //当前电量
        int total = intent.getIntExtra(BatteryManager.EXTRA_SCALE,1);       //总电量

        double ratio = currLevel / total;

        return ratio;
    }


}
